package life.system.search.controller;


import life.system.common.exception.BizCodeEnume;
import life.system.common.to.es.SkuEsModel;
import life.system.common.utils.R;
import life.system.search.service.ElasticsearchService;
import life.system.search.vo.SearchParam;
import life.system.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/search/product")
public class ElasticsearchController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    /**
     * 商品上架
     */
    @PostMapping("/save")
    public R productStatusUp(@RequestBody SkuEsModel skuEsModels) {
        boolean flag;
        try {
            flag = elasticsearchService.productStatusUp(skuEsModels);
        } catch (Exception e) {
            log.error("ElasticSaveController商品上架错误:", e);
            return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
        }

        if (flag) {
            return R.ok();
        } else {
            return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
        }
    }


    /**
     * 商品上架
     */
    @PostMapping("/del/{skuId}")
    public R productDel(@PathVariable("skuId") Integer skuId) {
        boolean flag;
        try {
            flag = elasticsearchService.productDel(skuId);
        } catch (Exception e) {
            log.error("ElasticSaveController商品上架错误:", e);
            return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
        }

        if (flag) {
            return R.ok();
        } else {
            return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
        }
    }


    /**
     *
     */
    @GetMapping("/query")
    public R listPage(SearchParam searchParam) {

        String queryString = searchParam.getKeyword();
        searchParam.set_queryString(queryString);

        SearchResult result = elasticsearchService.search(searchParam);
        return R.ok().put("data",result);
    }

}
